package com.newenergy.wisehome.gateway.account;


import android.app.Dialog;
import android.os.AsyncTask;
import android.support.design.widget.TextInputEditText;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.newenergy.wisehome.R;
import com.newenergy.wisehome.gateway.manager.BLLocalFamilyManager;
import com.newenergy.wisehome.ui.fragment.BaseFragment;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.broadlink.account.BLAccount;
import cn.com.broadlink.account.params.BLRegistParam;
import cn.com.broadlink.base.BLAppSdkErrCode;
import cn.com.broadlink.base.BLBaseResult;
import cn.com.broadlink.base.BLLoginResult;

/**
 * A simple {@link Fragment} subclass.
 */
public class RegisterFragment extends BaseFragment {

    @BindView(R.id.tv_page)
    TextView mTvPage;
    @BindView(R.id.et_name)
    TextInputEditText mEtName;
    @BindView(R.id.btn_code)
    Button mBtnCode;
    @BindView(R.id.et_code)
    TextInputEditText mEtCode;
    @BindView(R.id.et_pwd)
    TextInputEditText mEtPwd;
    @BindView(R.id.et_repwd)
    TextInputEditText mEtRepwd;
    @BindView(R.id.btn_register)
    Button mBtnRegister;

    private String mCountryCode = "0086";
    private String mAccount;
    private Dialog mLoadingDialog;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_register;
    }

    @Override
    public void init(View rootView) {
        mTvPage.setText("注册");
    }

    @OnClick({R.id.btn_back, R.id.tv_back, R.id.btn_code, R.id.btn_register})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                doBack();
                break;
            case R.id.tv_back:
                doBack();
                break;
            case R.id.btn_code:
                getVerifyCode();
                break;
            case R.id.btn_register:
                registerAction();
                break;
        }
    }

    private void registerAction() {
        String vCode = mEtCode.getText().toString();
        String password = mEtPwd.getText().toString();
        String repassword = mEtRepwd.getText().toString();
        if (TextUtils.isEmpty(vCode) || TextUtils.isEmpty(password)) {
            toast("验证码或密码不能为空！");
            return;
        }
        if (!password.equals(repassword)) {
            toast("两次密码不一致！");
            return;
        }
        new RegisterTask().execute(vCode, password);
    }

    private void getVerifyCode() {
        String phone = mEtName.getText().toString();
        new GetVerifyCodeTask().execute(phone);
    }

    //获取手机验证码
    private class GetVerifyCodeTask extends AsyncTask<String, Void, BLBaseResult> {
        private String account;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected BLBaseResult doInBackground(String... params) {
            //短信验证码
            account = params[0];
            return BLAccount.sendRegVCode(account, "+" + mCountryCode);
        }

        @Override
        protected void onPostExecute(BLBaseResult result) {
            super.onPostExecute(result);
            if (result != null && result.getError() == BLAppSdkErrCode.SUCCESS) {
                toast("验证码获取成功。");
            } else if (result != null) {
                toast("验证码获取失败：error = " + result.getError() + " msg = " + result.getMsg());
                Log.i(TAG, "验证码获取失败：error = " + result.getError()
                        + " msg = " + result.getMsg());
            } else {
                toast("验证码获取失败：网络错误");
            }
        }
    }

    private class RegisterTask extends AsyncTask<String, Void, BLLoginResult> {
        private String uerPassword;

        //创建默认家庭是否成功
        private String createFamilyId = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showLoading("正在注册。。。");
        }

        @Override
        protected BLLoginResult doInBackground(String... params) {
            uerPassword = params[1];
            BLRegistParam registParam = new BLRegistParam();
            registParam.setSex("male");
            registParam.setCode(params[0]);
            if (mCountryCode != null) {
                registParam.setCountrycode(mCountryCode);
            }
            registParam.setNickname(mAccount);
            registParam.setPhoneOrEmail(mAccount);
            registParam.setPassword(uerPassword);
            BLLoginResult result = BLAccount.regist(registParam, null);
            if (result != null && result.succeed()) {
                BLLoginResult loginResult = BLAccount.login(mAccount, uerPassword);
                if (loginResult != null && loginResult.succeed()) {
                    BLLocalFamilyManager familyManager = BLLocalFamilyManager.getInstance();
                    familyManager.isLogin = true;
                    familyManager.saveBLUserInfo(result);
                }
            }
            return result;
        }

        @Override
        protected void onPostExecute(BLLoginResult result) {
            super.onPostExecute(result);
            dismissLoading();
            if (result != null && result.getError() == BLAppSdkErrCode.SUCCESS) {
                toast("注册成功");
                startWithPop(new GatewayManageFragment());
//                doBack();
            } else if (result != null) {
                toast("注册失败：error = " + result.getError() + "  msg = " + result.getMsg());
                Log.e(TAG, "注册失败：error = " + result.getError() + "  msg = " + result.getMsg());
            } else {
                toast("注册失败：网络错误");
            }
        }
    }
}
